<?php
namespace app\sys\model;
use think\Validate;
use think\Db;
use app\base\model\Base;
class SinglepageM extends Base
{

    protected function _V($scene,$data)
    {
        $rule = [
            'page_name' => 'require',
            'content' => 'require',
        ];
        $msg = [];
        $field = [
            'page_name'=>'单页面名称',
            'content'=>'内容',
        ];
        $validate = new Validate($rule,$msg,$field);
        $validate->scene('add', ['page_name','content']);
        $validate->scene('edit', ['page_name','content']);
        $result = $validate->scene($scene)->check($data);
        if($result === false)
        {
            return $validate->getError();
        }
        else
        {
            return true;
        }

    }

    /**
     * 新增数据
     * @return mixed
     */

    public function add($data)
    {
        //验证数据
        $res = $this->_V('add',$data);
        if($res !== true)
        {
            $this->code = -1;
            $this->msg = $res;
            return false;
        }
        $insertData = [];
        //判断用户
        $insertData['admin_id'] = session('admin_id');
        $insertData['page_name'] = $data['page_name'];
        $insertData['content'] = $data['content'];
        $id = Db::table('sys_singlepage')->insertGetId($insertData);
        if(!$id)
        {
            $this->code = -1;
            $this->msg = '新增失败';
            return false;
        }
        return true;
    }

    /**
     * 全部数据
     */
    public function lst($page = 15)
    {
        $data = Db::table('sys_singlepage')->where('is_usable',1)->field('id,page_name')->paginate($page);
        return $data;
    }

    /**
     * 修改数据
     * @param $data
     * @return bool
     */
    public function edit($data)
    {
        $res = $this->_V('edit',$data);
        if($res !== true)
        {
            $this->code = -1;
            $this->msg = $res;
            return false;
        }
        $insertData = [];
        $insertData['page_name'] = $data['page_name'];
        $insertData['content'] = $data['content'];

        $id = Db::table('sys_singlepage')->where('id',$data['id'])->update($insertData);
        if(!$id)
        {
            $this->code = -1;
            $this->msg = '修改失败';
            return false;
        }
        return true;
    }

    /**
     * 删除数据
     * @param $id
     */
    public function del($id)
    {
        return Db::table('sys_singlepage')->where('id',$id)->update(['is_usable'=>0]);
    }
}
